<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-document-copy" size="mini" @click="exporFormVisible = true">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="sn码" value="1"></el-option>
              <el-option label="包名" value="2"></el-option>
              <el-option label="归属" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>

    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="110" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="160" align="center" prop="app_package" label="应用包名"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="120" align="center" prop="sn_value" label="SN码"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="120" align="center" prop="batch_id" label="批次"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" @click="getdeleteLabel(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>

    <el-dialog title="远程清除应用数据功能" :visible.sync="exporFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" :rules="rules" ref="ruleForm">
        <el-form-item label="应用包名" label-width="100px" prop="app_package">
          <el-input v-model="addForm.app_package" class="add_select" placeholder="请输入应用包名" :maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="类型:" label-width="100px" prop="status">
          <el-radio-group v-model="addForm.type">
            <el-radio :label="1">单条</el-radio>
            <el-radio :label="2">多条</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="typeShow">
          <el-form-item label="SN" label-width="100px" prop="sn">
            <el-input v-model="addForm.sn" class="add_select" placeholder="请输入SN码" :maxlength="30"></el-input>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="归属" label-width="100px">
            <el-select v-model="usernames" placeholder="请选择归属" filterable @change="infoChange" style="width:100%">
              <el-option v-for="(item,index) in affiliation" :key="index" :label="`${item.username} - ${item.title}`" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次" label-width="100px">
            <el-select v-model="addForm.bId" multiple placeholder="请选择批次" style="width:100%">
              <el-option v-for="(item,index1) in batchArray" :key="index1" :label="item.batch" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exporFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" size="mini" round @click="getaddClearApp('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryClearApp, addClearApp, deleteClearApp } from "@/api/lock.js";
import deleteDialog from "@/components/deleteDialog";
import { getAscription, getBatchTwo } from "@/api/equipment.js";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "应用包名", "SN码", "批次", "创建时间"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      exporFormVisible: false,
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), sn: undefined, app_package: undefined, username: undefined },
      //添加表单
      addForm: { sn: "", app_package: "", type: 1, bId: "" },
      rules: { sn: [{ required: true, message: "请输入SN", trigger: "blur" }], app_package: [{ required: true, message: "请输入应用包名", trigger: "blur" }] },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      affiliation: [],
      batchArray: [],
      usernames: '',
    }
  },
  computed: {
    typeShow() {
      return this.addForm.type == 1 ? true : false
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getqueryClearApp()
    this.getAscriptions()
  },
  methods: {
    infoChange(val) {
      this.addForm.bId = undefined
      this.getBatchTwos(val)
    },
    //设备维护获取归属用户信息
    getAscriptions() {
      getAscription({ userId: localStorage.getItem("ID") }).then(res => {
        //this.snParams = res.data.sort((a, b) => a.username.localeCompare(b.username))
        this.affiliation = res.data.sort((x, y) => {
          let reg = /[a-zA-Z0-9]/
          if (reg.test(x.username) || reg.test(y.username)) {
            if (x.username > y.username) {
              return 1
            } else if (x.username < y.username) {
              return -1
            } else {
              return 0
            }
          } else {
            return x.username.localeCompare(y.username)
          }
        })
      }).catch(err => {
        this.affiliation = []
      })
    },
    //根据ID获取批次列表
    getBatchTwos(id) {
      let data = { userId: id }
      getBatchTwo(data).then(res => {
        this.batchArray = res.data
      }).catch(err => {
        this.batchArray = []
      })
    },
    //删除
    getdeleteLabel(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteClearApp(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryClearApp()
      }).catch(err=>{
        console.log(err,'err');
      })
    },
    //添加
    getaddClearApp(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.bId = addForm.bId.toString()
          console.log('------',addForm)
          addClearApp(addForm).then(res => {
            this.$message.success(res.msg)
            this.exporFormVisible = false
            this.getqueryClearApp()
          })
        } else {
          return false;
        }
      });
    },
    getqueryClearApp() {
      queryClearApp(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      });
    },
    //搜索,1:sn码,2,归属
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.sn = this.searchTable
          this.getqueryClearApp();
          break;
        case '2':
          this.listQuery.app_package = this.searchTable
          this.getqueryClearApp();
          break;
        case '3':
          this.listQuery.username = this.searchTable
          this.getqueryClearApp();
          break;
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryClearApp();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryClearApp();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), sn: undefined, app_package: undefined, username: undefined }
      this.getqueryClearApp()
    },
    addFormclose() {
      this.$nextTick(() => {
        this.addForm = { sn: "", app_package: "", type: 1, bId: "" }
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>